<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>上传图片</title>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
	<div style="border: 1px solid red;">
		<h2>打开需要上传的文件 multiple属性多选  accept限制选择文件类型</h2>
		<!-- <input type="file" id="file" accept=".java" onchange="uploadfile(event);" /> -->
		<input type="file" id="file1" multiple onchange="uploadfile(event);" />
		<div id="result1"></div>
	</div>

	<br>
	<br>

	<div style="border: 1px solid red;">
		<h2>显示本地图片，点击按钮上传（多文件需要在回显的时候稍作修改）</h2>
		<input type="file" id="file2" accept="image/*" onchange="uploadfile2(event);" />
		<div id="result2">
			<img src="" alt="" id="img2" >
		</div>
		<input type="button" value="点击上传" id="button2" onclick="submitFunc2();" />
	</div>
	
	<br>
	<br>

	<div style="border: 1px solid red;">
		<h2>根据显示上传成功后的路径，显示服务器上的图片文件（多文件需要在回显的时候稍作修改）</h2>
		<input type="file" id="file3" accept="image/*" onchange="uploadfile3(event);" />
		<div id="result3">
			<img src="" alt="" id="img3" >
		</div>
	</div>
	
	<br>
	<br>
	
	<div style="border: 1px solid red;">
		<h2>js 触发input框的事件，兼容iOS</h2>
		<input style="display:none" type="file" id="file4" accept="image/*"/>
		<div id="result4">
			点击选择图片
			<img src="" alt="" id="img4" >
		</div>
	</div>
	
	<script>
    // 展示上传的文件
    function uploadfile(event) {
        //多种方式获取file
        //var files = document.getElementById('file1').files[0];
        //var files = $("#file1")[0].files;
        var files = event.target.files;
        for(var i=0;i<files.length;i++)
       	{
        	var file = files[i];
        	var fileName = file.name;
    		var fileSize = file.size;
    		console.log("读取文件："+fileName+",大小为："+fileSize)
    		
    		var reads = new FileReader();
        	reads.readAsText(file, 'utf-8');
            reads.onload = function (e) {
                console.log('读取操作完成时触发 ---> ',e)
                
                // document.getElementById('result').innerText = this.result
                // document.getElementById('result').innerText = e.target.result
                
                $("#result1").append(e.target.result);
            };
            reads.onloadstart = function(e) {
                console.log('读取操作开始时触发 ---> ', e)
            }
            reads.onloadend = function(e) {
            	//不管是失败还是成功都会触发
                console.log('读取操作结束时（要么成功，要么失败）触发 ---> ', e)
            }
            reads.onprogress = function(e) {
                console.log('读取进度 ---> ', e)
            }
            reads.onabort = function(e) {
                console.log('读取中断时触发 ---> ', e)
            }
            reads.onerror = function(e) {
                console.log('读取操作发生错误时触发 ---> ', e)
            }
       	}
    }

    // 显示本地资源，点击按钮上传
    function uploadfile2(event) {
        let reads = new FileReader();
        file = document.getElementById('file2').files[0];
        reads.readAsDataURL(file);
        reads.onload = function (e) {
            document.getElementById('img2').src = this.result;
        };
    }
    function submitFunc2()
    {
    	var files = $("#file2")[0].files;
    	var succes_callback = function(data){
			console.log(data);
    	}
    	var error_callback = function(err){
    		console.log(err);
    	}
    	ajaxFunc(files,{},succes_callback,error_callback);
    }
    
    
    //根据显示上传成功后的路径，显示服务器上的图片文件
    function uploadfile3() {
    	var files = $("#file3")[0].files;
    	var succes_callback = function(data){
			console.log(data);
			var reuslt = JSON.parse(data);
			for(var key in reuslt.data)
			{
				$("#img3").attr("src",reuslt.data[key]);
			}
			
    	}
    	var error_callback = function(err){
    		console.log(err);
    	}
    	ajaxFunc(files,{},succes_callback,error_callback);
    }
    
    
  	//隐藏的input框的change事件
	$("#file4").bind("change",function(e){
		var files = $("#file4")[0].files;
    	var succes_callback = function(data){
			console.log(data);
			var reuslt = JSON.parse(data);
			for(var key in reuslt.data)
			{
				$("#img4").attr("src",reuslt.data[key]);
			}
    	}
    	var error_callback = function(err){
    		console.log(err);
    	}
    	ajaxFunc(files,{},succes_callback,error_callback);
	});
	//触发input框的点击事件，通过点击事件，触发input框弹出选择文件，进而触发input框的change事件
	$("#result4").bind("click",function(event){
		click_index = $(this).attr("index");
		mockClick("#file4");
	});
	//触发click事件
	var mockClick = function(selector) {
	    //获取btn
	    var btn = document.querySelector(selector);
	    //创建event
	    var event = document.createEvent("MouseEvents");
	    //初始化event
	    event.initMouseEvent("click",true,true,document.defaultView,0,0,0,0,0,false,false,false,false,0,null);
	    //触发事件
	    btn.dispatchEvent(event);
	}
    
    
    // files:文件对象数组 
    // param：普通参数json
    // succes_callback：成功回调  
    // error_callback：失败回调
    function ajaxFunc(files,param,succes_callback,error_callback){
    	if(files.length==0)
    	{
    		alert("没有需要上传的文件");
    		return false;
    	}
    	
    	var formData = new FormData();  // 创建form对象
    	for(var i=0;i<files.length;i++)
    	{
    		var name = files[i].name;
    		formData.append(name, files[i]);  // 通过append向form对象添加数据
    		formData.append('text_param', "普通字符串参数");  // 如果还需要传替他参数的话
    	}
		
		$.ajax({
			url: '/servlet/UploadHandleServlet', //请求的接口地址
			type: 'POST',
			cache: false, //上传文件不需要缓存
			data: formData,
			processData: false, // 不要去处理发送的数据
			contentType: false, // 不要去设置Content-Type请求头
			success: function(data){
				//上传成功
				succes_callback(data);
			},
			error: function(err){
				error_callback(err);
			}
		})
    }
</script>
</body>
</html>